package day05;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author zouran
 * createDate：2024/7/3  16:04
 */

public class UploadTCPServer {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(10000);
        while (true) {
            Socket socket = server.accept();
            new Thread(() -> {
                try {
                    handleImg(socket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }
    }

    public static void handleImg(Socket socket) throws IOException {
        InputStream input = socket.getInputStream();
        OutputStream output = socket.getOutputStream();
        String path = "D:\\Users\\13055\\Desktop\\re.png";
        OutputStream save = new FileOutputStream(path);
        byte[] bytes = new byte[1024];
        int len;
        while ((len = input.read(bytes)) != -1) {
            save.write(bytes, 0, len);
        }
        save.close();
        String message = "上传成功";
        output.write(message.getBytes(StandardCharsets.UTF_8));
        socket.shutdownOutput();
        socket.close();
    }
}
